<template>
  <uni-popup ref="popup" type="bottom" @change="handlePopupChange">
    <view class="plan-editor">
      <!-- 头部工具栏 -->
      <view class="editor-header">
        <text class="title">{{ isEditMode ? '编辑计划' : '新建计划' }}</text>
        <view class="actions">
          <uni-icons 
            type="close" 
            size="24" 
            color="#666" 
            @click="closeEditor"
          ></uni-icons>
        </view>
      </view>

      <!-- 表单内容（优化滚动容器） -->
      <scroll-view 
        class="editor-content"
        scroll-y
        :scroll-top="scrollTop"
        :style="{ height: contentHeight + 'px' }"
        @touchmove="handleTouchMove"
        @scroll="handleScroll"
      >
        <!-- 标题 -->
        <view class="form-item">
          <text class="label">标题</text>
          <textarea 
            v-model="form.title"
            placeholder="输入计划标题"
            class="input-textarea"
            auto-height
          ></textarea>
        </view>

        <!-- 优先级 -->
        <view class="form-item">
          <text class="label">优先级</text>
          <view class="priority-options">
            <view 
              v-for="opt in priorityOptions"
              :key="opt.value"
              class="option"
              :class="{ active: form.priority === opt.value }"
              @click="form.priority = opt.value"
            >
              <view class="indicator" :class="opt.value"></view>
              <text>{{ opt.label }}</text>
            </view>
          </view>
        </view>

        <!-- 内容编辑器 -->
        <view class="form-item">
          <text class="label">详细内容</text>
          <SimpleTextEditor
            v-model="form.content"
            placeholder="输入计划详情..."
            :disabled="loading"
            :max-length="5000"
            @confirm="submitForm"
          />
        </view>

        <!-- 子任务列表 -->
        <view class="form-item">
          <view class="subtask-header">
            <text class="label">子任务</text>
            <view class="add-btn" @click="addSubTask">
              <uni-icons type="plus" size="16" color="#2775b6"></uni-icons>
              <text>添加</text>
            </view>
          </view>
          <view 
            v-for="(task, index) in form.subTasks"
            :key="task.id"
            class="subtask-item"
          >
            <checkbox 
              :checked="task.completed"
              @change="toggleSubTask(task.id)"
              color="#2775b6"
            />
            <input 
              v-model="task.text"
              placeholder="输入子任务"
              class="subtask-input"
              @blur="saveSubTask(task)"
              :disabled="loading"
            />
            <uni-icons 
              type="trash" 
              size="16" 
              color="#f5222d"
              @click="removeSubTask(index)"
            ></uni-icons>
          </view>
        </view>
      </scroll-view>

      <!-- 底部按钮（固定在编辑器底部） -->
      <view class="editor-footer">
        <button 
          class="btn delete" 
          v-if="isEditMode"
          @click="confirmDelete"
          :disabled="loading"
        >
          <uni-icons type="trash" size="16" color="white"></uni-icons>
          <text>删除</text>
        </button>
        <button 
          class="btn confirm" 
          @click="submitForm"
          :disabled="loading"
        >
          <uni-icons type="checkmarkempty" size="16" color="white"></uni-icons>
          <text>{{ isEditMode ? '保存更改' : '创建计划' }}</text>
        </button>
      </view>
    </view>
  </uni-popup>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { usePlanStore } from '@/stores/planStore'
import SimpleTextEditor from '@/components/functional/SimpleTextEditor.vue'

const props = defineProps({
  folderName: {
    type: String,
    required: true
  }
})

const emit = defineEmits(['saved', 'deleted'])

const planStore = usePlanStore()
const popup = ref(null)
const contentHeight = ref(400)
const loading = ref(false)
const scrollTop = ref(0)

// 表单数据
const form = reactive({
  id: null,
  title: '',
  content: '',
  priority: 'medium',
  subTasks: []
})

// 状态标记
const isEditMode = ref(false)
const priorityOptions = [
  { label: '高', value: 'high' },
  { label: '中', value: 'medium' },
  { label: '低', value: 'low' }
]

// 动态计算内容高度
onMounted(() => {
  const systemInfo = uni.getSystemInfoSync()
  // 留出底部按钮和头部空间
  contentHeight.value = systemInfo.windowHeight * 0.6 - 100
})

// 处理弹窗状态变化
const handlePopupChange = (e) => {
  if (e.show) {
    // 弹窗打开时重置滚动位置
    scrollTop.value = 0
  }
}

// 处理触摸事件（解决真机滚动问题）
const handleTouchMove = (e) => {
  // 允许默认滚动行为
}

// 处理滚动事件
const handleScroll = (e) => {
  scrollTop.value = e.detail.scrollTop
}

// 打开编辑器
const open = (planId = null) => {
  resetForm()
  isEditMode.value = !!planId

  if (planId) {
    const plan = planStore.currentPlans.find(p => p.id === planId)
    if (plan) {
      form.id = plan.id
      form.title = plan.title
      form.content = plan.content || ''
      form.priority = plan.priority
      form.subTasks = [...(plan.subTasks || [])]
    }
  }

  popup.value.open()
}

// 关闭编辑器
const closeEditor = () => {
  popup.value.close()
}

// 重置表单
const resetForm = () => {
  form.id = null
  form.title = ''
  form.content = ''
  form.priority = 'medium'
  form.subTasks = []
}

// 子任务操作
const addSubTask = () => {
  form.subTasks.push({
    id: Date.now().toString(),
    text: '',
    completed: false
  })
}

const toggleSubTask = (taskId) => {
  const task = form.subTasks.find(t => t.id === taskId)
  if (task) task.completed = !task.completed
}

const removeSubTask = (index) => {
  form.subTasks.splice(index, 1)
}

const saveSubTask = (task) => {
  if (!task.text.trim()) {
    removeSubTask(form.subTasks.findIndex(t => t.id === task.id))
  }
}

// 删除计划
const confirmDelete = () => {
  uni.showModal({
    title: '删除计划',
    content: '确定要删除这个计划吗？删除后不可恢复',
    success: async (res) => {
      if (res.confirm) {
        try {
          loading.value = true
          await planStore.deletePlan(form.id)
          uni.showToast({ title: '删除成功' })
          emit('deleted')
          closeEditor()
        } catch (err) {
          console.error('删除失败:', err)
          uni.showToast({ title: '删除失败', icon: 'none' })
        } finally {
          loading.value = false
        }
      }
    }
  })
}

// 提交表单
const submitForm = async () => {
  if (!form.title.trim()) {
    uni.showToast({ title: '请输入标题', icon: 'none' })
    return
  }

  try {
    loading.value = true
    
    const validSubTasks = form.subTasks
      .filter(t => t.text.trim())
      .map(t => ({
        ...t,
        text: t.text.trim()
      }))

    const planData = {
      title: form.title.trim(),
      content: form.content,
      priority: form.priority,
      subTasks: validSubTasks
    }

    if (isEditMode.value) {
      await planStore.updatePlan(form.id, planData)
      uni.showToast({ title: '更新成功' })
    } else {
      await planStore.addPlan(planData)
      uni.showToast({ title: '创建成功' })
    }
    
    emit('saved')
    closeEditor()
  } catch (err) {
    console.error('保存失败:', err)
    uni.showToast({ title: '保存失败', icon: 'none' })
  } finally {
    loading.value = false
  }
}

// 暴露方法
defineExpose({ open })
</script>

<style scoped>
.plan-editor {
  background-color: white;
  border-radius: 16px 16px 0 0;
  max-height: 80vh;
  display: flex;
  flex-direction: column;
  padding: 0 16px;
  box-sizing: border-box;
  /* 确保编辑器容器正确布局 */
  height: 100%;
}

.editor-header {
  padding: 16px;
  border-bottom: 1px solid var(--border-color);
  display: flex;
  justify-content: space-between;
  align-items: center;
  /* 固定头部 */
  flex-shrink: 0;
}

.title {
  font-size: 18px;
  font-weight: 500;
  color: var(--text-primary);
}

/* 优化滚动区域 */
.editor-content {
  flex: 1;
  padding: 16px 0;
  width: 100%;
  box-sizing: border-box;
  /* 关键修复：确保在iOS真机可滚动 */
  -webkit-overflow-scrolling: touch;
  overflow: auto;
}

.form-item {
  margin-bottom: 24px;
  width: 100%;
  box-sizing: border-box;
}

.label {
  display: block;
  font-size: 14px;
  color: var(--text-secondary);
  margin-bottom: 8px;
}

.input-textarea {
  border: 1px solid var(--border-color);
  border-radius: 8px;
  padding: 12px;
  font-size: 16px;
  width: 100%;
  box-sizing: border-box;
  background-color: white;
}

.priority-options {
  display: flex;
  gap: 12px;
}

.option {
  flex: 1;
  display: flex;
  align-items: center;
  padding: 8px 12px;
  border: 1px solid var(--border-color);
  border-radius: 8px;
  cursor: pointer;
  box-sizing: border-box;
}

.option.active {
  border-color: var(--primary-color);
}

.indicator {
  width: 12px;
  height: 12px;
  border-radius: 50%;
  margin-right: 8px;
}

.indicator.high {
  background-color: #f5222d;
}

.indicator.medium {
  background-color: #faad14;
}

.indicator.low {
  background-color: #52c41a;
}

.subtask-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.add-btn {
  display: flex;
  align-items: center;
  color: var(--primary-color);
  font-size: 14px;
}

.add-btn text {
  margin-left: 4px;
}

.subtask-item {
  display: flex;
  align-items: center;
  padding: 8px 0;
  border-bottom: 1px dashed var(--border-color);
  width: 100%;
}

.subtask-input {
  flex: 1;
  margin: 0 12px;
  padding: 8px 0;
  font-size: 14px;
  background-color: transparent;
}

/* 固定底部按钮 */
.editor-footer {
  display: flex;
  padding: 12px 0;
  border-top: 1px solid var(--border-color);
  width: 100%;
  /* 确保固定在底部 */
  flex-shrink: 0;
}

.btn {
  height: 44px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 16px;
  border-radius: 8px;
  margin: 0 4px;
  padding: 0 16px;
}

.btn.delete {
  background-color: #f5222d;
  color: white;
  flex: 1;
}

.btn.confirm {
  background-color: var(--primary-color);
  color: white;
  flex: 2;
}

.btn:disabled {
  opacity: 0.6;
}

.btn text {
  margin-left: 6px;
}
</style>